<?php
namespace app\api\controller;
use think\Db;
use think\Request;
use app\admin\model\Member;
use app\admin\model\Project;
use app\admin\model\Task;
use app\admin\model\Standard;

class Index
{
    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改（2006-2018） - 你值得信赖的PHP框架【API接口模块】</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>';
    }

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    public $appkey = "hangtianxinxi-prod";//apiKey
    public $secret = "cWBLqQVWYM8bmQDX13PLGhZJfKX1EjP3EnbjpVmPAx8CmZnB3g8Sbp79FUZlyQcc";//apiSecret
    public $host = "https://data-sync.dream-sports.cn/api/";

    /**
     * 初始化
     * @author wuyaorong
     * @since 2023/08/12
     */
    protected function initialize(Request $request = null)
    {
        parent::initialize($request); // TODO: Change the autogenerated stub
        
    }

    /**
     * @return json
     */
    public function post($url, $post_data)
    {
        $timestamp = $this->get_msectime();
        // $post_data = json_encode($post_data);
        $nonce = $this->get_rand_str(15);
        $sign = $this->getSign($url, $timestamp, $nonce);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->host . $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => $post_data,
            CURLOPT_HTTPHEADER => array(
                "client-key: " . $this->appkey,
                "signature: " . $sign,
                "nonce: ". $nonce,
                "timestamp: " . $timestamp,
                "api-version: 1.3.2"
            ),
        ));
        // 关闭SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($curl);
        //$headerSize = curl_getinfo($curl);
        //$header = substr($response, 0, $headerSize);
        // 打印响应头
        // halt($headerSize);
        curl_close($curl);
        return $response;
    }

    /**
     * 获取签名
     * @param $post_data
     * @param bool $timestamp
     * @return string
     */
    public function getSign($url, $timestamp, $nonce)
    {
        $signString = "GET&$url&$timestamp&$nonce&$this->secret";
        // halt($signString);
        $sign = hash('sha256', $signString);
        // halt($sign);
        //echo "签名原始串:$signString<br/>"."签名后:$sign <br/>";
        return $sign;
    }

    //返回当前的毫秒时间戳
    public function get_msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }


    //随机字符串
    public function get_rand_str($len){
        $str = "1234567890asdfghjklqwertyuiopzxcvbnmASDFGHJKLZXCVBNMPOIUYTREWQ";
        return substr(str_shuffle($str),0,$len);
    }

    //获取同步运动结果
    //请求格式
    //{ "type": 1, "startTimestamp": 1634123953948, "endTimestamp": 1634123974579}
    public function synchronous()
    {
        $datas = input();
        $res = $this->post('/isport-data/sync-sport-result', $datas);
        halt($res);
        return $res;
    }

    //运动结果条数同步
    //请求格式
    //{ "type": 1, "startTimestamp": 1634123953948, "endTimestamp": 1634123974579}
    public function resultSynchronous()
    {
        $datas = input();
        $res = $this->post('/isport-data/sync-sport-result-total', $datas);
        halt($res);
        return $res;
    }

    //查询学生最近测试记录
    //请求格式
    //{"type": 1, "testerNumber": 20211013180754, "idCard": 411321187009143215X, "nfcNumber": 211003}
    public function checkResult()
    {
        $datas = input();
        $res = $this->post('/isport-data/recent-test-result', $datas);
        halt($res);
        return $res;
    }

    //查询运动结果
    //请求格式
    //{ "type": 1, "startTimestamp": 1634123953948, "endTimestamp": 1634123974579,"pageNo":1,"pageSize":1000}
    public function synchronousResult($datas)
    {
        //$datas = input();
        $res = $this->post('/isport-data/sync-sport-pagination-result', $datas);
        $res = json_decode($res,true);
        $member = new Member();
        $project = new Project();
        $task = new Task();
        $standard = new Standard();
         // halt($res);
        $data = [];
        $rows = $res['result']['rows'];
        foreach ($rows as &$vs) {
            $mlist = $member->where('roll',$vs['testerNumber'])->find();
            if ($mlist) { //判断匹配学籍号
                $vs['tbid'] = $vs['id'];
                $vs['memberId'] = $mlist['id'];
                $vs['schoolId'] = $mlist['organization'];
                $vs['gradeId'] = $mlist['grade'];
                $vs['classId'] = $mlist['class'];
                $vs['departmentsId'] = $mlist['superior'];
                $vs['professionalId'] = $mlist['professional'];
                $vs['projectId'] = $project->where('code',$vs['itemCode'])->value('id');
                $vs['taskId'] = 0; //暂无任务id
                $stanArr = [];
                if ($vs['taskId']) {
                     $staid = $task->where('id',$vs['taskId'])->value('standard');
                     $stanArr = json_decode($standard->where('id',$staid)->value('standard'),true);
                }else{
                    //没有任务情况下的测试标准
                     //$stanArr = json_decode($standard->where(['organization'=>$vs['schoolId']])->value('standard'),true);
                }
                if ($stanArr) {
                    foreach ($stanArr as $vv) {
                         if ($vv['sex']==$mlist['gender']) {
                            switch ($vv['conditions']) {//判断成绩评级
                                case 'gt':
                                    if ($mlist['score']>$vv['target']) {
                                        $vs['rating'] = $vv['level'];
                                        $vs['score'] = $vv['score'];
                                    }
                                    break;
                                case 'egt':
                                    if ($mlist['score']>=$vv['target']) {
                                        $vs['rating'] = $vv['level'];
                                        $vs['score'] = $vv['score'];
                                    }
                                    break;
                                case 'lt':
                                    if ($mlist['score']<$vv['target']) {
                                        $vs['rating'] = $vv['level'];
                                        $vs['score'] = $vv['score'];
                                    }
                                    break;
                                case 'elt':
                                    if ($mlist['score']<=$vv['target']) {
                                        $vs['rating'] = $vv['level'];
                                        $vs['score'] = $vv['score'];
                                    }
                                    break;
                                case 'between':
                                    if ($mlist['score']>=$vv['target'][0]&&$mlist['score']<=$vv['target'][1]) {
                                        $vs['rating'] = $vv['level'];
                                        $vs['score'] = $vv['score'];
                                    }
                                    break;
                                
                                default:
                                    $vs['rating'] = 0;
                                    break;
                            }
                         }
                     }
                }
                
                $data[] = $vs;
            }
        }
        unset($vs);
        return $data;
    }

    /**
     * 同步运动记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function tongbuSport()
    {
        // 获取当前日期
        $currentDate = date('Y-m-d');

        // 当天的开始时间
        $startTime = strtotime($currentDate)*1000; // 将日期转换为毫秒时间戳

        // 当天的结束时间
        $endTime = strtotime($currentDate . ' 23:59:59')*1000; // 将日期和时间转换为毫秒时间戳
        $datas = [
            "type"=>1, //数据类型 1：校内体育测试 2：校内体育锻炼 3：校外体育云作业 4：校园云体锻
            "startTimestamp"=> $startTime,
            "endTimestamp"=> $endTime,
            "pageNo"=> 1,
            "pageSize"=> 1000
        ];
        $result = $this->synchronousResult($datas);//获取第三方同步数据
        halt($result);
        $tbnum = 0;
        foreach ($result as $vv) {
            $id = Db::name('sport_record')->where('tbid',$vv['tbid'])->value('id');
            if (!$id) {
                Db::name('sport_record')->insert($vv);
                $tbnum++;
            }
        }
        echo "同步".$tbnum."条";
    }
}
